<?php
/*
 * IKPHP 爱客开源社区 @copyright (c) 2012-3000 IKPHP All Rights Reserved 
 * @author 小麦
 * @Email:ikphp@sina.cn
 * @爱客网特有ikmail消息组件系统 下期继续优化
 */
namespace IKPHP\Apps\Home\Controllers;



use IKPHP\Common\Controllers\FrontendController;
use IKPHP\Common\Models\User;
use IKPHP\Common\Models\MessageBox;
use IKPHP\Apps\Space\Models\UserFollow;

class MessageController extends FrontendController {
	
	private $userid = 0;

    public function initialize()
    {
        parent::initialize();
    	// 访问者控制
		if ($this->visitor){
			$this->userid = $this->visitor['userid'];
		}
		$this->mod      =  new MessageBox();
		$this->user_mod =  new User();
    }
	//写邮件
	public function writeAction($touserid) {
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}
		
		$userid = $this->userid; 
		if ($userid == $touserid || ! $touserid || !is_numeric($touserid)){
			return $this->error ( "Sorry！自己不能给自己发送消息的！& 对方为空!" );
		}
			
		$strTouser = $this->user_mod->getOneUser ( $touserid ); 
		!$strTouser && $this->error ( '呃...你想要的东西不在这儿' );
		// 获取post
		if (IS_POST) {

		    if ($this->security->checkToken()) {
            
				$msg_title = $this->_post('title');
				$msg_content = $this->_post('content');
				if($msg_title=='' || $msg_content=='') return $this->error("标题和内容都不能为空！");
				if(ck_strlen($msg_title) > 64) return  $this->error('标题很长很长很长很长...^_^');
				if(ck_strlen($msg_content) > 500) return  $this->error('发这么多内容干啥^_^');
				
				$res = $this->mod->sendMessage($userid,$touserid,$msg_title,$msg_content);
				if($res){
					return $this->_redirect('home/message/ikmail/outbox');
				}else{
					return $this->error ( '呃...发站内信失败了' );
				}
				
			
		    }else{
		    	return $this->error ( '呃...已经超时了' );
		    }
			
		}
		$this->assign ( 'strTouser', $strTouser );
		$this->_config_seo ( array (
				'title' => '发送短消息',
				'subtitle' => '消息中心' 
		) );
	}
	//收件箱 发件箱
	public function ikmailAction($type){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}
		if(!in_array(trim($type), array('outbox','inbox','unread','choose','spam'))) return $this->error ( '呃...你想要的东西不在这儿' );
		
		$userid = $this->userid;
		$unreadnum = $this->mod->count("touserid = '$userid' and isread =0 and isinbox=0");//未读邮件数目
		$spamnum = $this->mod->count("touserid = '$userid' and isspam =1 and isinbox=0");//垃圾邮件数目
		$inmenu = array(
				'inbox' => array('url'=>U('home/message/ikmail/inbox'), 'text'=>'所有消息'),
				'unread' => array('url'=>U('home/message/ikmail/unread'), 'text'=>'未读消息('.$unreadnum.')'),
				'spam' => array('url'=>U('home/message/ikmail/spam'), 'text'=>'垃圾消息('.$spamnum.')'),
				);
		$this->assign ( 'ik', $type );
		$this->assign('unreadnum',$unreadnum);
		$this->assign ( 'inmenu', $inmenu );
		$this->assign ( 'userid', $userid );
		switch ($type) {
			// 我的发件箱
			case "outbox" :
				$where = array("userid = '$userid' and isoutbox = 0", "order" => "addtime desc", "limit" => 20);
				$arrMessages = $this->mod->find($where);
				$arrMessage = array();
				if($arrMessages){
					foreach($arrMessages->toArray() as $key=>$item){
						$arrMessage[] = $item;
						$arrMessage[$key]['touser']	 = $this->user_mod->getOneUser($item['touserid']);
						$arrMessage[$key]['content'] = sub_str(strip_tags($item["content"]),200);
						$arrMessage[$key]['addtime'] =  date('Y-m-d H:i',$item['addtime']);
					}
				}
				$this->assign ( 'arrMessage', $arrMessage );
				$this->_config_seo ( array (
						'title' => '我的发件箱',
						'subtitle' => '消息中心'
				) );
				$this->view->pick ('message/outbox');			
				break;
			case "inbox" :
				$where = array("touserid = '$userid' and isspam <> 1 and isinbox = 0", "order" => "addtime desc", "limit" => 20);
				$arrMessages = $this->mod->find($where);
				$arrMessage = array();
				if($arrMessages){ 
					foreach($arrMessages->toArray() as $key=>$item){
						$arrMessage[] = $item;
						$arrMessage[$key]['user']	 = $this->user_mod->getOneUser($item['userid']);
						$arrMessage[$key]['content'] = sub_str(strip_tags($item["content"]),200);
						$arrMessage[$key]['addtime'] =  date('Y-m-d H:i',$item['addtime']);
					}				
				}
				$this->assign ( 'arrMessage', $arrMessage );	
				$this->_config_seo ( array (
						'title' => '我的收件箱',
						'subtitle' => '消息中心'
				) );
				$this->view->pick ('message/inbox');
				break;
			case "unread" :
				$where = array("touserid = '$userid' and isread = 0 and isinbox = 0", "order" => "addtime desc", "limit" => 20);
				$arrMessages = $this->mod->find($where);
				$arrMessage = array();
				if($arrMessages){
					foreach($arrMessages->toArray() as $key=>$item){
						$arrMessage[] = $item;
						$arrMessage[$key]['user']	 = $this->user_mod->getOneUser($item['userid']);
						$arrMessage[$key]['content'] = sub_str(strip_tags($item["content"]),200);
						$arrMessage[$key]['addtime'] =  date('Y-m-d H:i',$item['addtime']);
					}
				}
				$this->assign ( 'arrMessage', $arrMessage );
				$this->_config_seo ( array (
						'title' => '我的收件箱',
						'subtitle' => '消息中心'
				) );
				$this->view->pick ('message/inbox');
				break;
			case "choose" :
				$where = array("userid = '$userid'", "order" => "addtime desc");
				$followUsers = UserFollow::find($where);
				$arrFollowUser = array();
				if($followUsers){
					foreach($followUsers->toArray() as $item){
						$arrFollowUser[] =  $this->user_mod->getOneUser($item['userid_follow']);
					}	
				}
				$this->assign ( 'arrFollowUser', $arrFollowUser );
				$this->_config_seo ( array (
						'title' => '写信-选择收件人',
						'subtitle' => '消息中心'
				) );
				$this->view->pick ('message/choose');				
				break;	
			case "spam" :
				$where = array("touserid = '$userid' and isspam = 1 and isinbox = 0", "order" => "addtime desc", "limit" => 20);
				$arrMessages = $this->mod->find($where);
				$arrMessage = array();
				if($arrMessages){
					foreach($arrMessages->toArray() as $key=>$item){
						$arrMessage[] = $item;
						$arrMessage[$key]['user']	 = $this->user_mod->getOneUser($item['userid']);
						$arrMessage[$key]['content'] = sub_str(strip_tags($item["content"]),200);
						$arrMessage[$key]['addtime'] =  date('Y-m-d H:i',$item['addtime']);
					}
				}
				$this->assign ( 'arrMessage', $arrMessage );				
				$this->_config_seo ( array (
						'title' => '我的收件箱',
						'subtitle' => '消息中心'
				) );
				$this->view->pick ('message/inbox');
				break;				
			// 默认
			default :
				return $this->error ( '呃...你想要的东西不在这儿' );
		}
	}

	//显示
	public function showAction($messageid){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}		
		$userid = $this->userid;
		if (!is_numeric($messageid) || empty($messageid)){
			return $this->error ( '呃...你想要的东西不在这儿' );
		}
		
		$where = array("messageid = '$messageid'");
		$arrMessages = $this->mod->findFirst($where);
		if(!$arrMessages){
			return $this->error ( '呃...你想要的东西不在这儿' );
		}
		$arrMessages = $arrMessages->toArray();
		$arrMessages['addtime'] = date('Y-m-d H:i',$arrMessages['addtime']);
		
		if($arrMessages['userid'] == $userid)
		{
			//发往对方
			if($arrMessages['isoutbox']==1){
				return $this->_redirect('message/ikmail/inbox');				
			}
			$touser = $this->user_mod->getOneUser($arrMessages['touserid']);//来自哪位用户
			$strUserinfo = '<span class="m">发往：'.$touser['username'].'（'.$touser['area']['areaname'].'）</span>';
			$type = 'outbox';
			$this->_config_seo ( array (
					'title' => '我发送的消息',
					'subtitle' => '消息中心'
			) );
		}
		if($arrMessages['touserid'] == $userid)
		{
			//接收的信息
			if($arrMessages['isinbox']==1){
				return $this->_redirect('message/ikmail/inbox');
			}
			$touser = $this->user_mod->getOneUser($arrMessages['userid']);//来自哪位用户
			$strUserinfo = '<span class="m">来自：'.$touser['username'].'（'.$touser['area']['areaname'].'）</span>';
			$type = 'inbox';
			//isread设为已读
			$where = array("touserid = '$userid' and isread = 0 and messageid = '$messageid'");
			$resMeg = $this->mod->findFirst($where);
			if($resMeg)
			{
				$resMeg->save(array('isread'=>1));
			}
			$this->_config_seo ( array (
					'title' => '我接收的消息',
					'subtitle' => '消息中心'
			) );
		}
		if($arrMessages['userid'] == 0 && $arrMessages['touserid']==$userid)
		{
			//接收的信息 系统消息
			if($arrMessages['isinbox']==1){
				return $this->_redirect('message/ikmail/inbox');
			}
			$strUserinfo = '<span class="m">来自：<span class="sys_doumail_big">系统邮件</span> </span>';
			$touser = $this->user_mod->getOneUser($arrMessages['userid']);//来自哪位用户;
			//isread设为已读
			$where = array("touserid = '$userid' and isread = 0 and messageid = '$messageid'");
			$resMeg = $this->mod->findFirst($where);
			if($resMeg)
			{
				$resMeg->save(array('isread'=>1));
			}
			$this->_config_seo ( array (
					'title' => '我接收的系统消息',
					'subtitle' => '消息中心'
			) );
		}
		
		$this->assign ( 'touser', $touser );
		$this->assign ( 'strUserinfo', $strUserinfo );
		$this->assign ( 'arrMessages', $arrMessages );
		$this->assign ( 'type', $type );

	}
	//操作
	public function doingAction(){
		//访问控制
		if(!$this->visitor){return $this->_redirect('home/user/login');}	
		$d = $this->_get ( 'd', 'trim' );
		if(!in_array(trim($d), array('del','spam','all'))) return $this->error ( '呃...你想要的东西不在这儿dd' );
		
		$userid = $this->userid;
		$messageid = empty($_POST['messageid']) ? $_GET['messageid'] : $_POST['messageid'];

		switch($d){
		
			//删除
			case "del":
				$type = $this->_get('type');
				if($type=='inbox')
				{
					$status = $this->mod->findFirst("touserid='$userid' and messageid='$messageid'");
					$status && $status->save(array('isinbox'=>1));
				}
				if($type=='outbox')
				{
					$status = $this->mod->findFirst("userid='$userid' and messageid='$messageid'");
					$status && $status->save(array('isoutbox'=>1));
				}
				$this->_redirect('home/message/ikmail/'.$type);
				break;
		
			case "spam":
				$status = $this->mod->findFirst(" (touserid='$userid' or userid = 0) and messageid='$messageid'");
				$status && $dd= $status->save(array('isspam'=>1)); 
				$this->_redirect('home/message/ikmail/spam');
				break;
		
			case "all":
				$type = $this->_post('type');
				$mc_submit = $this->_post('mc_submit','trim');
				if($mc_submit=='删除' && $type=='inbox')
				{
					for($i=0; $i<count($messageid); $i++)
					{
						$status = $this->mod->findFirst("touserid='$userid' and messageid='$messageid[$i]'");
						$status && $status->save(array('isinbox'=>1));
					}
					//删除
					$this->mod->find("isinbox=1 and isoutbox=1")->delete();
					$this->_redirect('home/message/ikmail/inbox');
				}
				if($mc_submit =='删除' && $type=='outbox')
				{
					for($i=0; $i<count($messageid); $i++)
					{
						$status = $this->mod->findFirst("userid='$userid' and messageid='$messageid[$i]'");
						$status && $status->save(array('isoutbox'=>1));
					}
					//删除
					$this->mod->find("isinbox=1 and isoutbox=1")->delete();
					$this->_redirect('home/message/ikmail/outbox');
				}
				if($mc_submit =='垃圾消息')
				{
					for($i=0; $i<count($messageid); $i++)
					{
						$status = $this->mod->findFirst("touserid='$userid' and messageid='$messageid[$i]'");
						$status && $status->save(array('isspam'=>1));
					}
					$this->_redirect('home/message/ikmail/spam');
				}
				if($mc_submit=='标记为已读')
				{
					for($i=0; $i<count($messageid); $i++)
					{
						$status = $this->mod->findFirst("touserid='$userid' and messageid='$messageid[$i]'");
						$status && $status->save(array('isread'=>1));
					}
					$this->_redirect('home/message/ikmail/inbox');
				}
		
				break;
		}
	}	
}